const child_process = require('child_process');
const fs = require("fs");
const path = require("path");

function readline(query) {
	const rl = require("readline").createInterface({
		input: process.stdin,
		output: process.stdout
	});
	return new Promise((resolve, reject) => {
		rl.question(query, answer => {
			rl.close();
			resolve(answer);
		});
	});
}

function exec(cmd) {
	return new Promise(function(resolve, reject) {
		child_process.exec(cmd, resolve);
	});
}

function record() {
	return new Promise(function(resolve, reject) {
		var proc = child_process.spawn('mode2', ['-m', '-d', '/dev/lirc0'])
		var s = '';
		var prev_at = 0;
		var handle = setInterval(function() {
			if (prev_at && Date.now() - prev_at > 500) {
				proc.kill()
				clearInterval(handle)
				resolve(s);
			}
		}, 1e3);
		proc.stdout.on('data', function(data) {
			s += data;
			if (!prev_at) {
				s = s.replace(/^[\s\S]+\/dev\/lirc0[\s\S]+\d+\n/, function(x0) {
					prev_at = Date.now();
					return '';
				})
			} else {
				prev_at = Date.now();
			}
		})
	});
}

async function main() {
	await exec(`/etc/init.d/lircd stop`)
	let filename = process.argv[2];
	if (!filename)
		return console.log(`node ${process.argv0} [FILE]`)
	let text
	try {
		text = fs.readFileSync(filename, 'utf8')
	} catch (e) {
		text = `begin ${path.basename(filename)}

name  aircon
flags RAW_CODES
eps            30
aeps          100

gap          19991

	begin raw_codes
	end raw_codes

end remote`
		fs.writeFileSync(filename, text);
	}
	let add = ""
	while (true) {
		let name = await readline('key name: ')
		if (!name) break;
		let s = await record();
		add += `\n          name ${name}\n`
		add += s.split(/\s+/).filter(x => x).map(x => Math.round(x / 10) * 10).join(' ')
	}
	text = text.replace(/\s+end raw_codes/, function(x0) {
		return add + x0;
	})
	fs.writeFileSync(filename, text);
	await exec(`/etc/init.d/lircd restart`)
}

main();